<template>
    <div class="tokutei-exam">
        <div class="content-wrapper">
            <!-- 考试介绍 -->
            <el-card class="exam-intro">
                <div class="intro-content">
                    <div class="exam-fields">
                        <h3>考试领域：</h3>
                        <el-row :gutter="20">
                            <el-col :span="8" v-for="field in examFields" :key="field.name">
                                <div class="field-item">
                                    <el-icon class="field-icon"><component :is="field.icon" /></el-icon>
                                    <h4>{{ field.name }}</h4>
                                    <p>{{ field.description }}</p>
                                </div>
                            </el-col>
                        </el-row>
                    </div>
                </div>
            </el-card>

            <!-- 考试选择 -->
            <div class="exams-section">

                <div class="exams-grid">
                    <div v-for="exam in exams" :key="exam.id" class="exam-card">
                        <div class="exam-header">
                            <!--<img :src="exam.icon" :alt="exam.name" class="exam-icon" />-->
                            <div class="exam-info">
                                <h4>{{ exam.examName }}</h4>
                                <p>{{ exam.description }}</p>
                                <div class="exam-meta">
                                    <!--<el-tag size="small" type="info">{{ exam.category }}</el-tag>-->
                                    <el-tag size="small" :type="getDifficultyType(exam.difficulty)">{{ exam.difficulty }}</el-tag>
                                </div>
                            </div>
                        </div>

                        <div class="exam-details">
                            <div class="detail-item">
                                <span class="label">考试时长：</span>
                                <span class="value">{{ exam.durationMin }}分钟</span>
                            </div>
                            <div class="detail-item">
                                <span class="label">题目数量：</span>
                                <span class="value">{{ exam.questionNum }}题</span>
                            </div>
                            <div class="detail-item">
                                <span class="label">及格分数：</span>
                                <span class="value">{{ exam.passScore }}分</span>
                            </div>
                        </div>

                        <div class="exam-actions">
                            <el-button
                                    type="primary"
                                    size="large"
                                    @click="startExamBtn(exam)"
                                    :loading="startingExam === exam.id"
                            >
                                开始考试
                            </el-button>
                            <!--<el-button-->
                                    <!--type="info"-->
                                    <!--size="large"-->
                                    <!--@click="viewExamDetail(exam)"-->
                            <!--&gt;-->
                                <!--查看详情-->
                            <!--</el-button>-->
                        </div>
                    </div>
                </div>

                <!-- 分页 -->
                <div class="pagination-wrapper">
                    <el-pagination
                            v-model:current-page="currentPage"
                            v-model:page-size="pageSize"
                            :page-sizes="[12, 24, 36, 48]"
                            :total="totalExams"
                            layout="total, sizes, prev, pager, next, jumper"
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                    />
                </div>
            </div>

         </div>
    </div>
</template>

<script setup>
  import { ref, onMounted, computed, watch } from 'vue'
  import { useRouter,useRoute  } from 'vue-router'
  import { ElMessage } from 'element-plus'
  import { Search } from '@element-plus/icons-vue'
  import {
    listExamslevel,getExamsList,
  } from '@/api/system'

      const router = useRouter()
      const route = useRoute()

      const examFields = ref([
        {
          name: '食品加工',
          description: '食品制造、加工、包装等相关技能',
          icon: 'Food'
        },
        {
          name: '餐饮服务',
          description: '餐厅服务、烹饪、食品卫生等技能',
          icon: 'Restaurant'
        },
        {
          name: '护理服务',
          description: '老年人护理、医疗辅助等技能',
          icon: 'User'
        },
        {
          name: '农业',
          description: '农作物种植、畜牧养殖等技能',
          icon: 'Plant'
        },
        {
          name: '汽车维修',
          description: '汽车检测、维修、保养等技能',
          icon: 'Car'
        },
        {
          name: '酒店服务',
          description: '客房服务、前台接待等技能',
          icon: 'House'
        }
      ])

      const courses = ref([
        {
          id: 1,
          name: '特定技能基础课程',
          description: '全面了解特定技能考试内容和要求',
          duration: '3个月',
          level: '初级',
          image: '/src/assets/index/study.jpg'
        },
        {
          id: 2,
          name: '专业技能强化班',
          description: '针对特定领域的专业技能培训',
          duration: '2个月',
          level: '中级',
          image: '/src/assets/index/study.jpg'
        },
        {
          id: 3,
          name: '模拟考试训练',
          description: '真实考试环境模拟，提高通过率',
          duration: '1个月',
          level: '高级',
          image: '/src/assets/index/study.jpg'
        }
      ])

      const examSchedule = ref([
        {
          date: '2024-03-15',
          field: '食品加工',
          location: '东京考试中心',
          deadline: '2024-02-15'
        },
        {
          date: '2024-04-20',
          field: '餐饮服务',
          location: '大阪考试中心',
          deadline: '2024-03-20'
        },
        {
          date: '2024-05-10',
          field: '护理服务',
          location: '名古屋考试中心',
          deadline: '2024-04-10'
        }
      ])


  // 获取考试类型
  const fetchExamsLists = async () => {
    const examTypeId = route.query.id
    try {
      const params = {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        examTypeId: examTypeId
      }

      const response = await getExamsList(params)
      if (response.code === 200) {
        exams.value = response.rows || []
        totalExams.value = response.total || 0
      }
    } catch (error) {
      console.error('获取考试列表失败:', error)
    } finally {
    }
  }
// 获取考试类型
      const fetchLists = async () => {
        const examTypeId = route.query.id
        try {
          const params = {
            pageNum: 1,
            pageSize: 100,
            examTypeId: examTypeId
          }

          const response = await listExamslevel(params)
          if (response.code === 200) {
            examFields.value = response.rows || []
          }
        } catch (error) {
          console.error('获取考试类型列表失败:', error)
        } finally {
        }
      }
      onMounted(() => {
        // 初始化数据
        fetchLists()
        fetchExamsLists()
      })

      // 监听路由参数变化，重新获取数据
      watch(
        () => route.query.id,
        (newId, oldId) => {
          if (newId !== oldId) {
            // 重置分页
            currentPage.value = 1
            // 重新获取数据
            fetchLists()
            fetchExamsLists()
          }
        },
        { immediate: false }
      )

      const enrollCourse = (courseId) => {
        ElMessage.success('课程报名成功！')
        // 这里可以跳转到课程详情页面
      }

      const bookExam = (exam) => {
        router.push('/exam-booking')
      }

      // 考试选择相关数据
      const selectedCategory = ref('all')
      const selectedDifficulty = ref('all')
      const searchKeyword = ref('')
      const currentPage = ref(1)
      const pageSize = ref(12)
      const startingExam = ref(null)
      const totalExams = ref(0)
      const exams = ref([])

      // 模拟考试数据
      const mockExams = ref([
        {
          id: 1,
          name: '日语N5基础语法考试',
          description: '测试日语N5级别的基础语法知识，包括助词、动词变化等',
          category: 'JLPT',
          difficulty: '初级',
          duration: 60,
          totalQuestions: 50,
          icon: 'https://via.placeholder.com/80x80/409EFF/FFFFFF?text=N5',
          passScore: 60,
          maxScore: 100
        },
        {
          id: 2,
          name: '商务日语会话考试',
          description: '商务场景下的日语会话能力测试，涵盖日常商务交流',
          category: '特定技能',
          difficulty: '中级',
          duration: 90,
          totalQuestions: 60,
          icon: 'https://via.placeholder.com/80x80/67C23A/FFFFFF?text=商务',
          passScore: 70,
          maxScore: 100
        },
        {
          id: 3,
          name: '日语听力理解考试',
          description: '测试日语听力理解能力，包括日常对话和新闻听力',
          category: 'JLPT',
          difficulty: '中级',
          duration: 75,
          totalQuestions: 40,
          icon: 'https://via.placeholder.com/80x80/E6A23C/FFFFFF?text=听力',
          passScore: 65,
          maxScore: 100
        },
        {
          id: 4,
          name: 'JFT基础考试',
          description: '日本语能力测试基础级别，适合初学者',
          category: 'JFT',
          difficulty: '初级',
          duration: 45,
          totalQuestions: 30,
          icon: 'https://via.placeholder.com/80x80/F56C6C/FFFFFF?text=JFT',
          passScore: 55,
          maxScore: 100
        },
        {
          id: 5,
          name: '日语写作表达考试',
          description: '测试日语写作表达能力，包括短文写作和邮件写作',
          category: '特定技能',
          difficulty: '高级',
          duration: 120,
          totalQuestions: 80,
          icon: 'https://via.placeholder.com/80x80/909399/FFFFFF?text=写作',
          passScore: 75,
          maxScore: 100
        },
        {
          id: 6,
          name: '日语阅读理解考试',
          description: '测试日语阅读理解能力，包括文章阅读和问题解答',
          category: 'JLPT',
          difficulty: '中级',
          duration: 90,
          totalQuestions: 70,
          icon: 'https://via.placeholder.com/80x80/409EFF/FFFFFF?text=阅读',
          passScore: 70,
          maxScore: 100
        }
      ])

      // 计算属性 - 筛选后的考试
      const filteredExams = computed(() => {
        let filtered = mockExams.value

        // 按分类筛选
        if (selectedCategory.value !== 'all') {
          filtered = filtered.filter(e => e.category === selectedCategory.value)
        }

        // 按难度筛选
        if (selectedDifficulty.value !== 'all') {
          filtered = filtered.filter(e => e.difficulty === selectedDifficulty.value)
        }

        // 按关键词搜索
        if (searchKeyword.value) {
          filtered = filtered.filter(e => 
            e.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
            e.description.toLowerCase().includes(searchKeyword.value.toLowerCase())
          )
        }

        return filtered
      })

      // 获取难度类型
      const getDifficultyType = (difficulty) => {
        switch (difficulty) {
          case '初级': return 'success'
          case '中级': return 'warning'
          case '高级': return 'danger'
          default: return 'info'
        }
      }


      // 开始考试
      const startExamBtn = async (exam) => {
        try {
          startingExam.value = exam.id
          ElMessage.success('考试开始成功！')
          
          // 跳转到考试页面
          router.push({
            path: '/exam-room',
            query: { 
              sessionId: `session_${Date.now()}`,
              examId: exam.id
            }
          })
          
        } catch (error) {
          console.error('开始考试失败:', error)
          ElMessage.error('开始考试失败，请稍后重试')
        } finally {
          startingExam.value = null
        }
      }

      // 查看考试详情
      const viewExamDetail = (exam) => {
        router.push(`/exam-detail/${exam.id}`)
      }

      const handleSizeChange = (size) => {
        pageSize.value = size
        currentPage.value = 1
        fetchExamsLists()
      }

      const handleCurrentChange = (page) => {
        currentPage.value = page
        fetchExamsLists()
      }

</script>

<style scoped>
    .tokutei-exam {
        padding: 20px;
        max-width: 1200px;
        margin: 0 auto;
    }

    .page-header {
        text-align: center;
        margin-bottom: 30px;
    }

    .page-header h1 {
        font-size: 2.5rem;
        color: #303133;
        margin-bottom: 10px;
    }

    .subtitle {
        font-size: 1.2rem;
        color: #606266;
    }

    .content-wrapper {
        display: flex;
        flex-direction: column;
        gap: 20px;
    }

    .card-header {
        font-weight: bold;
        font-size: 1.2rem;
    }

    .exam-intro .intro-content {
        line-height: 1.6;
    }


    .exam-fields h3 {
        margin-bottom: 15px;
        color: #303133;
    }

    .field-item {
        text-align: center;
        padding: 20px;
        border: 1px solid #ebeef5;
        border-radius: 8px;
        height: 100%;
        margin: 20px 0;
        cursor: pointer;
    }

    /* 为el-col添加额外的上下间距 */
    .exam-fields .el-col {
        margin-bottom: 20px;
    }

    .field-icon {
        font-size: 2rem;
        color: #409eff;
        margin-bottom: 10px;
    }

    .field-item h4 {
        margin: 10px 0;
        color: #303133;
    }

    .field-item p {
        color: #606266;
        font-size: 0.9rem;
    }

    .courses-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
        gap: 20px;
    }

    .course-card {
        border: 1px solid #ebeef5;
        border-radius: 8px;
        overflow: hidden;
        transition: transform 0.3s ease;
    }

    .course-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }

    .course-image img {
        width: 100%;
        height: 200px;
        object-fit: cover;
    }

    .course-info {
        padding: 20px;
    }

    .course-info h3 {
        margin: 0 0 10px 0;
        color: #303133;
    }

    .course-info p {
        color: #606266;
        margin-bottom: 15px;
    }

    .course-meta {
        display: flex;
        justify-content: space-between;
        margin-bottom: 15px;
    }

    .duration, .level {
        background: #f0f2f5;
        padding: 4px 8px;
        border-radius: 4px;
        font-size: 0.9rem;
        color: #606266;
    }

    /* 考试选择部分样式 */
    .exams-section {
        background: white;
        border-radius: 12px;
        padding: 25px;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        margin-top: 20px;
    }

    .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 25px;
    }

    .section-header h3 {
        margin: 0;
        color: #2c3e50;
        font-size: 1.5rem;
    }

    .filter-controls {
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .exams-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
        gap: 25px;
        margin-bottom: 30px;
    }

    .exam-card {
        background: white;
        border: 1px solid #ebeef5;
        border-radius: 12px;
        padding: 25px;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        transition: transform 0.3s ease, box-shadow 0.3s ease;
    }

    .exam-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
    }

    .exam-header {
        display: flex;
        align-items: center;
        gap: 15px;
        margin-bottom: 15px;
    }

    .exam-icon {
        width: 60px;
        height: 60px;
        border-radius: 8px;
        object-fit: cover;
    }

    .exam-info h4 {
        margin: 0 0 5px 0;
        color: #2c3e50;
        font-size: 1.2rem;
    }

    .exam-info p {
        margin: 0;
        color: #666;
        font-size: 0.9rem;
        line-height: 1.4;
    }

    .exam-meta {
        margin-top: 10px;
        display: flex;
        gap: 8px;
    }

    .exam-details {
        margin-bottom: 20px;
        padding-bottom: 15px;
        border-bottom: 1px solid #eee;
    }

    .detail-item {
        display: flex;
        justify-content: space-between;
        margin-bottom: 8px;
        font-size: 0.9rem;
        color: #555;
    }

    .detail-item .label {
        font-weight: 500;
        color: #333;
    }

    .detail-item .value {
        font-weight: bold;
        color: #2c3e50;
    }

    .exam-actions {
        display: flex;
        gap: 10px;
        margin-top: 15px;
    }

    .pagination-wrapper {
        text-align: center;
        margin-top: 30px;
    }

    @media (max-width: 768px) {
        .tokutei-exam {
            padding: 15px;
        }

        .page-header h1 {
            font-size: 2rem;
        }

        .courses-grid {
            grid-template-columns: 1fr;
        }

        .exams-grid {
            grid-template-columns: 1fr;
        }

        .section-header {
            flex-direction: column;
            align-items: flex-start;
            gap: 15px;
        }

        .filter-controls {
            flex-wrap: wrap;
            gap: 8px;
        }
    }
</style>
